﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using TeamPrasioliteWarGame.Models;
using TeamPrasioliteWarGame.Controls.ErrorSuccessNotifier;

namespace TeamPrasioliteWarGame
{
    public partial class Attacks : System.Web.UI.Page
    {
        private List<Literal> literalList = new List<Literal>();
        private List<TextBox> textBoxList = new List<TextBox>();
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Entities db = new Entities();
            using (db)
            {
                var users = db.AspNetUsers.ToList();
                this.ListViewUsers.DataSource = users;
                this.ListViewUsers.DataBind();

                var userId = User.Identity.GetUserId();
                var userUnit = db.UserUnits.Include("GameUnit").Where(u => u.UserId == userId).ToList();

                this.ListViewUnits.DataSource = userUnit;
                this.ListViewUnits.DataBind();

                GetLabels(this.ListViewUnits);

                var username = this.User.Identity.Name;
                var user = db.AspNetUsers.SingleOrDefault(u => u.UserName == username);
                var userUnits = db.UserUnits
                    .Where(u => u.UserId == user.Id)
                    .ToList();

                for (int i = 0; i < literalList.Count; i++)
                {
                    literalList[i].Text = "/" + userUnits[i].Count.ToString();
                }
            }
        }

        private void GetLabels(Control control)
        {
            foreach (var contr in control.Controls)
            {
                GetLabels(contr as Control);
                var myContr = contr as Literal;
                if (myContr != null)
                {
                    literalList.Add(myContr);
                }
            }
        }

        private void GetTextBoxes(Control control)
        {
            foreach (var contr in control.Controls)
            {
                GetTextBoxes(contr as Control);
                var myContr = contr as TextBox;
                if (myContr != null)
                {
                    this.textBoxList.Add(myContr);
                }
            }
        }

        protected void ButtonAttack_Clicked(object sender, EventArgs e)
        {
            var usernameToAttack = this.UserToAttack.Text;
            Entities db = new Entities();
            using (db)
            {
                var defender = db.AspNetUsers.Include("UserUnits").SingleOrDefault(u => u.UserName == usernameToAttack);
                if (defender == null)
                {
                    this.UserToAttack.Text = "There aren't any selected users!!!";
                    return;
                }

                this.GetTextBoxes(this.ListViewUnits);

                var attackerId = User.Identity.GetUserId();
                var attacker = db.AspNetUsers.Include("UserUnits").SingleOrDefault(u => attackerId == u.Id);
                var userUnits = db.UserUnits
                    .Include("GameUnit")
                    .Where(u => u.UserId == attacker.Id)
                    .ToList();

                for (int i = 0; i < userUnits.Count; i++)
                {
                    if (userUnits[i].Count < int.Parse(textBoxList[i].Text))
                    {
                        ErrorSuccessNotifier.AddInfoMessage("You dont have that much  " + userUnits[i].GameUnit.Type);
                        Response.Redirect("~/Attacks.aspx");
                        return;
                    }
                }

                var combinedAttackPower = 0;
                for (int i = 0; i < userUnits.Count; i++)
                {
                    int unitAttackPower = userUnits[i].GameUnit.Attack;
                    combinedAttackPower += int.Parse(textBoxList[i].Text) * unitAttackPower;
                }

                var defenderUserUnits = db.UserUnits
                   .Include("GameUnit")
                   .Where(u => u.UserId == defender.Id)
                   .ToList();

                var combinedDefencePower = 0;
                for (int i = 0; i < defenderUserUnits.Count; i++)
                {
                    int unitDefencePower = defenderUserUnits[i].GameUnit.Defense * defenderUserUnits[i].GameUnit.HP / 20;
                    combinedDefencePower += unitDefencePower * defenderUserUnits[i].Count;
                }

                var counter = 0;
                if (combinedAttackPower > combinedDefencePower)
                {
                    foreach (var unitType in defender.UserUnits)
                    {
                        unitType.Count = (int)(unitType.Count - (int.Parse(textBoxList[counter].Text) / 3));
                        counter++;
                    }
                    var attackerUserProfile = attacker.ExtendUsers.FirstOrDefault();
                    var defenderUserProfile = defender.ExtendUsers.FirstOrDefault();

                    attackerUserProfile.Food += (int)(defenderUserProfile.Food / 2);
                    defenderUserProfile.Food = (int)(defenderUserProfile.Food / 2);
                    attackerUserProfile.Wood += (int)(defenderUserProfile.Wood / 2);
                    defenderUserProfile.Wood = (int)(defenderUserProfile.Wood / 2);
                    attackerUserProfile.Iron += (int)(defenderUserProfile.Iron / 2);
                    defenderUserProfile.Iron = (int)(defenderUserProfile.Iron / 2);
                }
                else
                {
                    foreach (var unitType in attacker.UserUnits)
                    {
                        unitType.Count = (int)(unitType.Count - (int.Parse(textBoxList[counter].Text) / 2));
                        counter++;
                    }
                }

                db.SaveChanges();
            }
        }

        protected void ButtonSelectUser_Command(object sender, CommandEventArgs e)
        {
            this.UserToAttack.Text = Convert.ToString(e.CommandArgument);
        }
    }
}